package com.example.netcenter.Log;


import android.util.Log;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * okhttp打印网络请求日志
 */
public class MyHttpLoggingInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public interface Logger {
        void log(String message);

        /**
         * A {@link Logger} defaults output appropriate for the current platform.
         */
        Logger DEFAULT = new Logger() {
            @Override
            public void log(String me) {
               // LogUtil.d(me);
            }
        };
    }

    public MyHttpLoggingInterceptor() {
        this(Logger.DEFAULT);
    }

    private MyHttpLoggingInterceptor(Logger logger) {
        this.logger = logger;
    }

    private final Logger logger;


    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        RequestBody requestBody = request.body();

        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();

        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;

        String requestStartMessage = "请求url--> " + request.method() + ' ' + request.url() + ' ' + protocol;

        Log.e("Conker",requestStartMessage);

        if (!hasRequestBody) {
            Log.e("Conker","no requestBody");
        } else if (bodyEncoded(request.headers())) {
            Log.e("Conker","--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            Log.e("Conker","请求参数:  "+buffer.readString(charset));

            Log.e("Conker","--> 请求体大小 " + request.method()
                    + " (" + requestBody.contentLength() + "-byte body)");
        }

//        if (logHeaders) {
//            if (hasRequestBody) {
//                // Request body headers are only present when installed as a network interceptor. Force
//                // them to be included (when available) so there values are known.
//                if (requestBody.contentType() != null) {
//                    logger.log("Content-Type: " + requestBody.contentType());
//                }
//                if (requestBody.contentLength() != -1) {
//                    logger.log("Content-Length: " + requestBody.contentLength());
//                }
//            }

//            Headers headers = request.headers();
//            for (int i = 0, count = headers.size(); i < count; i++) {
//                String name = headers.name(i);
//                // Skip headers from the request body as they are explicitly logged above.
//                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
//                    logger.log(name + ": " + headers.value(i));
//                }
//            }
//
//            if (!logBody || !hasRequestBody) {
//                logger.log("--> END " + request.method());
//            } else if (bodyEncoded(request.headers())) {
//                logger.log("--> END " + request.method() + " (encoded body omitted)");
//            } else {
//                Buffer buffer = new Buffer();
//                requestBody.writeTo(buffer);
//
//                Charset charset = UTF8;
//                MediaType contentType = requestBody.contentType();
//                if (contentType != null) {
//                    charset = contentType.charset(UTF8);
//                }
//
//                logger.log("");
//                logger.log(buffer.readString(charset));
//
//                logger.log("--> END " + request.method()
//                        + " (" + requestBody.contentLength() + "-byte body)");
//            }
//        }

        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        //请求时间
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        Log.e("Conker","请求返回code<-- " + response.code() + ' ' + response.message() + ' '
                + response.request().url() + " ("
                + bodySize + " body" + ')');
        Log.e("Conker","请求耗费时间:  " + tookMs + "ms");

//        if (logHeaders) {
//            Headers headers = response.headers();
//            for (int i = 0, count = headers.size(); i < count; i++) {
//                logger.log(headers.name(i) + ": " + headers.value(i));
//            }

//            if (!logBody || !HttpEngine.hasBody(response)) {
//                logger.log("<-- END HTTP");
//            } else if (bodyEncoded(response.headers())) {
//                logger.log("<-- END HTTP (encoded body omitted)");
//            } else {
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
//                        logger.log("");
                logger.log("Couldn't decode the response body; charset is likely malformed.");
//                        logger.log("<-- END HTTP");

                return response;
            }
        }

        if (contentLength != 0) {
//                    logger.log("");
            Log.e("Conker","请求返回内容<--  " + buffer.clone().readString(charset));
        }

//                logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
//            }
//        }

        return response;
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}
